import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '', // 从环境变量获取基础URL
  timeout: 5000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
});

// 加载实例
let loadingInstance = null;

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 显示加载状态
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 添加token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    // 关闭加载状态
    if (loadingInstance) loadingInstance.close();
    // 请求错误处理
    ElMessage.error('请求发生错误: ' + error.message);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 关闭加载状态
    if (loadingInstance) loadingInstance.close();

    const res = response.data;

    // 处理业务错误
    if (res.code !== 200) {
      ElMessage.error(res.message || '操作失败');
      // 处理特定错误码
      if (res.code === 401) {
        // 未授权，可能需要重新登录
        localStorage.removeItem('token');
        window.location.href = '/login';
      }
      return Promise.reject(new Error(res.message || 'Error'));
    }

    return res;
  },
  (error) => {
    // 关闭加载状态
    if (loadingInstance) loadingInstance.close();

    // 处理网络错误
    let errorMessage = '网络请求失败';
    if (error.response) {
      switch (error.response.status) {
        case 400:
          errorMessage = '请求参数错误';
          break;
        case 401:
          errorMessage = '未授权，请重新登录';
          localStorage.removeItem('token');
          window.location.href = '/login';
          break;
        case 403:
          errorMessage = '拒绝访问';
          break;
        case 404:
          errorMessage = '请求资源不存在';
          break;
        case 500:
          errorMessage = '服务器内部错误';
          break;
        default:
          errorMessage = `请求错误: ${error.response.status}`;
      }
    } else if (error.message.includes('timeout')) {
      errorMessage = '请求超时';
    } else if (error.message.includes('Network Error')) {
      errorMessage = '网络连接错误';
    }

    ElMessage.error(errorMessage);
    return Promise.reject(error);
  }
);

// 封装请求方法
const request = {
  get(url, params = {}, config = {}) {
    return service.get(url, { params, ...config });
  },

  post(url, data = {}, config = {}) {
    return service.post(url, data, config);
  },

  put(url, data = {}, config = {}) {
    return service.put(url, data, config);
  },

  delete(url, params = {}, config = {}) {
    return service.delete(url, { params, ...config });
  },

  // 上传文件
  upload(url, file, onUploadProgress) {
    const formData = new FormData();
    formData.append('file', file);
    return service.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress
    });
  },

  // 下载文件
  download(url, params = {}) {
    return service.get(url, {
      params,
      responseType: 'blob',
      timeout: 30000
    }).then(response => {
      const blob = new Blob([response.data]);
      const fileName = response.headers['content-disposition']?.split('filename=')[1] || 'download';
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = decodeURIComponent(fileName);
      link.click();
      URL.revokeObjectURL(link.href);
      return { success: true };
    });
  }
};

export default request;